# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generates HTML file with all dependencies from a js_unittest build target."""

import os
import sys
from argparse import ArgumentParser

_HTML_FILE_START = r'''<!DOCTYPE html>'''
_JS_MODULE = r'<script type="module" src="%s"></script>'
_JS_MODULE_REGISTER_TESTS = r'''
<script>
  // Push all entities to global namespace to be visible to the test harness:
  // ui/webui/resources/js/webui_resource_test.js
  const js_module_url = '%s';
  import(js_module_url).then(TestModule => {
    for (const name in TestModule) {
      window[name] = TestModule[name];
    }
  });
</script>
'''


def _process_js_module(input_file, output_filename):
  """Generates the HTML for a unittest based on JS Modules.

  Args:
    input_file: The path for the unittest JS module.
    output_filename: The path/filename for HTML to be generated.
  """

  # Map //ui/file_manager files to test URL:
  js_module_url = input_file.replace(
      'ui/file_manager/', 'chrome://file_manager_test/ui/file_manager/', 1)

  with open(output_filename, 'w') as out:
    out.write(_HTML_FILE_START + '\n')

    line = _JS_MODULE % (js_module_url)
    out.write(line + '\n')

    line = _JS_MODULE_REGISTER_TESTS % (js_module_url)
    out.write(line + '\n')


def main():
  parser = ArgumentParser()
  parser.add_argument(
      '-s', '--src_path', help='Path to //src/ directory', required=True)
  parser.add_argument(
      '-i',
      '--input',
      help='Input dependency file generated by js_library.py',
      required=True)
  parser.add_argument(
      '-o',
      '--output',
      help='Generated html output with flattened dependencies',
      required=True)
  parser.add_argument('-t', '--target_name', help='Test target name')
  args = parser.parse_args()

  # Convert from:
  # gen/ui/file_manager/file_manager/common/js/example_unittest.m.js_library
  # To:
  # ui/file_manager/file_manager/common/js/example_unittest.m.js
  path_test_file = args.input.replace('gen/', '', 1)
  path_test_file = path_test_file.replace('.js_library', '.js')
  _process_js_module(path_test_file, args.output)
  return


if __name__ == '__main__':
  main()
